﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Javascript's Method</title>
    <link rel="stylesheet" type="text/css" href="../common/qunit.css" />
    <script type="text/javascript" src="../common/jquery.js"></script>
    <script type="text/javascript" src="../common/qunit.js"></script>
    <script type="text/javascript">

        function demoThis() {
            var obj = {
                method: function () {
                    strictEqual(this, obj, "'this' reference the object which this method is invoked");

                    var self = this;
                    nested();

                    function nested() {
                        "use strict";
                        strictEqual(this, undefined, "nested function doesn't inherit 'this' from outer method");
                        strictEqual(self, obj);
                    }
                }
            };
            obj.method();
        }

        function Fool(prefix) {
            this.prefix = prefix;
        }

        Fool.prototype.fool = function (id) {
            return this.prefix + id;
        };

        function demoMethodCallEquivalency() {
            var f = new Fool("hello");

            equal(f.fool(1), "hello1");

            equal(Fool.prototype.fool.call(f, 8), "hello8", "'obj.method(parameter)' is equivalent with 'obj.method.call(obj,parameter)'");
        }

        function demoBind_InstanceMethod() {

            function add(b) {
                return this.a + b;
            }

            var o = { a: 1 };
            var fool = add.bind(o);

            equal(fool(8), 9);

            o.a = 100;
            equal(fool(8), 108);
        }

        function demoBind_GlobalFunction() {

            function add(x, y) {
                return x + y;
            }

            // 'this' is bound to null (not used here)
            // and the first parameter is bound to 100
            var fool = add.bind(null, 100);

            deepEqual([6, 8].map(fool), [106,108]);
        }

    </script>
</head>
<body>
    <h1 id="qunit-header">
        Method Demonstration</h1>
    <h2 id="qunit-banner">
    </h2>
    <div id="qunit-testrunner-toolbar">
    </div>
    <h2 id="qunit-userAgent">
    </h2>
    <ol id="qunit-tests">
    </ol>
    <div id="qunit-fixture">
        test markup, will be hidden</div>
    <script type="text/javascript">
        test("demo 'this'", demoThis);
        test("demo the equivalency between method invocation and call", demoMethodCallEquivalency);

        module("bind");
        test("bind first parameter to 'this' in instance method", demoBind_InstanceMethod);
        test("except binding 'this', it can still bind other parameters", demoBind_GlobalFunction);
    </script>
</body>
</html>
